async function getLocal(key) {
  const result = await chrome.storage.local.get([key]);
  return result[key];
}
function saveLocal(key, value) {
  chrome.storage.local.set({ [key]: value });
}
/*************************************************/
var userInfo = {};

async function getUserVal() {
  var userVal = await getLocal('userVal');
  if (userVal && typeof userVal === 'string') {
    userInfo = JSON.parse(userVal);
  }
}
getUserVal();
/******************************************************************/
// chrome.tabs.onCreated.addListener(function (tab) {
// 	console.log('标签被创建：',userInfo,tab)
// });
// chrome.windows.getCurrent({}, function (windowInfo) {
//   console.log("当前窗口信息:", windowInfo);
// });

function openPreviewPage(data) {
  chrome.tabs.create({
    url: '/preview/index.html'
  });
  console.log('向预览页发送数据：',data)
  setTimeout(() => {
    chrome.runtime.sendMessage({
      type: 'preview',
      data
    });
  }, 1500);
}
/******************************************************************/
var searchTab = {}, //存储搜索 Tab 对象
  searchStatus = {}, //存储平台搜索状态
  searchPlate = [], //存储搜索平台
  initParam, //存储初始化参数
  searchCompany, //存储搜索公司
  searchId, //存储搜索 ID
  searchJob, //存储搜索职位
  searchNames = {}, //存储搜索用户姓名[按平台分对象]
  initNames = [],
  searchData = {}, //存储搜索数据
  searchResult = []; //存储搜索结果
function getSearchParam(from = 'baidu') {
  if (!from) return false;
  searchData[from] = {
    name: searchNames[from].shift().trim(),
    company: searchCompany,
    jobs: searchJob
  };
}
/******************************************************************/

/******************************************************************/
async function startSearchAction({ data = {} }) {
  initParam = data;
  searchCompany = data.company.trim();
  searchId = data._id?.trim()||'';
  searchPlate = data.plate;
  const names = data.name.split(',').filter((name) => (name.trim() ? true : false));
  searchNames = {};
  initNames = [];
  searchPlate.forEach((plate) => {
    searchNames[plate] = names.slice();
  });
  initNames = names.slice();
  /***************************************/
  searchJob = data.job.split(',');
  searchResult = [];
  searchStatus = {};
  searchPlate.forEach((plate) => {
    searchStatus[plate] = 'process';
    getSearchParam(plate);
  });
  // 创建百度搜索新窗口
  if (searchPlate.includes('baidu')) {
    searchTab['baidu'] = await chrome.tabs.create({
      url: `https://www.baidu.com/s?wd=${searchData['baidu'].company} ${searchData['baidu'].name}`,
      active: false // 新窗口要打开的网址
    });
  }
  //创建搜狗搜索新窗口
  if (searchPlate.includes('sogou')) {
    searchTab['sogou'] = await chrome.tabs.create({
      url: `https://www.sogou.com/web?query=${encodeURIComponent(searchData['sogou'].company + ' ' + searchData['sogou'].name)}`,
      active: false // 新窗口要打开的网址
    });
  }
  //创建必应搜索新窗口
  if (searchPlate.includes('biying')) {
    searchTab['biying'] = await chrome.tabs.create({
      url: `https://cn.bing.com/search?q=${searchData['biying'].company + ' ' + searchData['biying'].name}`,
      active: false // 新窗口要打开的网址
    });
  }
}
function openResult(data) {
  if (!data.href) return false;
  chrome.tabs.create({
    url: data.href,
    active: false // 新窗口要打开的网址
  });
}
var searchOverTimer = {};
/******************************************************************/
function getSearchType(data) {
  const values = Object.values(searchStatus);
  const over = values.filter((v) => v == 'over');
  if (over?.length > 0 && over?.length == searchPlate?.length) {
    return 'over';
  }
  if (values.includes('process')) {
    return 'process';
  }
  return 'unstart';
}
/******************************************************************/
function dealSearchResult(list) {
  if (!list?.length) return [];
  const result = [];
  initNames.forEach((name) => {
    const item = list.filter((v) => v.name == name);
    if (item && item?.length) {
      result.push(...item);
    }
  });
  return result;
}
/*******************20241229 向浏览器活动窗口发送message数据************************************************/
function sendToActiveTab(params) {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    if (tabs && tabs[0]) {
      const tab = tabs[0];
      if(tab.url.includes('localhost')||tab.url.includes('cmzc.cc')){
        chrome.tabs.sendMessage(tab.id, params,(response)=>{
        });
      }
    }
  });
  //console.log('向浏览器活动窗口发送message数据：', params);
}
/**********************************************************/
function getSearchLength(){
  let length = 0;
  searchPlate.forEach((plate) => {
    let length2 = searchNames[plate].length;
    //console.info(plate,length2)
    if(length2>length)length = length2;
  });
  return initNames.length - length;
}
function updateResult2System(){
  const type = getSearchType();
  if(type!='over')return false;
  const list = dealSearchResult(searchResult);
  //console.log('搜索完成',searchId,list,searchResult)
  const backendUrl = 'https://fc-mp-5632fc40-f047-42f3-8072-39dbd210a30e.next.bspapp.com/human-admin/index/patentJob';
  const length = getSearchLength();
  const names = initNames.slice(0,length);
  fetch(backendUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body:JSON.stringify({
      _id:searchId,
      names:names,
      list
    })
  })
  .then(response => response.json())
  .then(data => {
    // 将数据发送回内容脚本或其他扩展部分
    console.log('服务端响应数据：',data)
  })
}
/******************************************************************/
function updateSearchResult(from) {
  
  const type = getSearchType();
  const result = dealSearchResult(searchResult);
  //console.log("更新搜索结果：", type);
  /***************二次判断 ******************/
  if(searchNames[from]?.length == 0){
    searchStatus[from] = 'over';
  }
  /*********************************************/
  const params = {
    status: 'resultupdate',
    data: { type, ...initParam, result, from }
  };
  chrome.runtime.sendMessage(params,(response) => {
    if (chrome.runtime.lastError) {
      //console.error('jiangxiuchuan No listener found:', chrome.runtime.lastError);
    } else {
      //console.log('Response:', response);
    }
  });
  /********************************/
  sendToActiveTab(params);
  /*********************************************/
  clearTimeout(searchOverTimer[from]);
  if (searchStatus[from] != 'over') {
    searchOverTimer[from] = setTimeout(
      (from) => {
        console.log('超时搜索:',from);
        searchStatus[from] = 'over';
        //searchNames[from] = [];
        updateSearchResult(from);
      },
      10000,
      from
    );
  }else{
    //console.log('判断是不是需要同步系统：',searchId,type);
    if(searchId&&type=='over' ){
      updateResult2System();
    }
  }

}
/******************************************************************/
function resetSearch() {
  searchStatus = {};
  searchPlate = [];
  searchCompany = '';
  searchId = '';
  searchJob = [];
  searchNames = {};
  initNames = [];
  searchData = {};
  searchResult = [];
}
/*********** */
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  //console.log("收到来自content-script的数据推送：", request);
  const from = request.from;
  /*********************************************************/
  if(request.type=='closetab'){
    chrome.tabs.remove(searchTab[from]?.id);
    return false;
  }
  /*********************************************************/
  if (request.type == 'searchupdate') {
    const type = getSearchType();
    if (type == 'unstart') {
      sendResponse({ status: 'resultupdate', data: { type } });
      return false;
    }
    sendResponse({ status: 'resultupdate', data: { type, ...initParam, result: dealSearchResult(searchResult) } });
  }
  if (request.type == 'searching') {
    startSearchAction(request);
    return false;
  }
  if (request.type == 'stopupdate') {
    resetSearch();
    return false;
  }
  if (request.type == 'searchready') {
    const data = searchData[from];
   
    if (!data){
      chrome.tabs.remove(searchTab[from]?.id);
    }else{
      sendResponse({ action: 'match', data }); //搜索打开成功，匹配搜索词
    }
    updateSearchResult(from);
  }
  //console.log('响应事件：',request.type)
  if (request.type == 'searchsuccess') {
    
    //单次搜索完成，提交搜索结果
    if (request.data) {
      searchResult.push(...request.data);
      //openResult(request.data);
      searchStatus[from] = 'process';
      updateSearchResult(from);
    }
    if (searchNames[from]?.length == 0||searchStatus[from] == 'over') {
      sendResponse({ action: 'over' });
      searchStatus[from] = 'over';
      //console.log(from,'平台搜索结束！！！')
      //chrome.tabs.remove(searchTab[from]?.id);
      updateSearchResult(from);
      return false;
    }
    getSearchParam(from);
    sendResponse({ action: 'search', data: searchData[from] });
  }
  /*********************************************************/
  /*********************************************************/
  /*********************************************************/
  /*********************************************************/

  if (request.type == 'preview') {
    openPreviewPage({
      ...request,
      uid: userInfo.user_id,
      nickname: userInfo.nickname,
      username: userInfo.username
    });
    sendResponse({ code: 200, msg: 'success' });
  } else if (request.type == 'user') {
    userInfo = request.data;
  } else if (request.type == 'init') {
    if (userInfo && userInfo.user_id) {
      sendResponse({ code: 200, msg: 'success', user: userInfo });
    } else {
      sendResponse({ code: 404, msg: 'not fount' });
    }
  }else if(request.type=='batchJob'){ //批量获取职位详情
	  console.log('批量获取职位详情',request);
  }
  return true;
});

// setTimeout(() => {
//   chrome.tabs.create({
//     url: "/preview/index.html",
//   });

//   setTimeout(() => {
//     chrome.runtime.sendMessage({
//       greeting: "你好，我是backgroundt呀，我主动发消息给后台！",
//     });
//   }, 5000);
// }, 10000);
